package dao.impl;

import dao.DoctorsDao;
import entity.Doctors;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import utils.DruidUtils;

import java.sql.Connection;
import java.util.List;

public class DoctorsDaoImpl implements DoctorsDao {


    @Override
    public Doctors queryById(Integer id) {
        return null;
    }

    @Override
    public List<Doctors> queryByDepartment(String department) {
        Connection conn = null;
        try {
            //从连接池获取连接
            conn = DruidUtils.getConnection();
            String s = "SELECT  id, title, user_id FROM doctors where department=? ";
            BasicRowProcessor basicRowProcessor = new BasicRowProcessor(new GenerousBeanProcessor());
            QueryRunner queryRunner = new QueryRunner();
            List<Doctors> query = queryRunner.query(conn, s,
                    new BeanListHandler<>(Doctors.class, basicRowProcessor), department);
            DruidUtils.close(null, conn);
            return query;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            DruidUtils.close(null, conn);
        }
        return null;
    }

    @Override
    public List<Doctors> queryAll() {
        Connection conn = null;
        try {
            //从连接池获取连接
            conn = DruidUtils.getConnection();
            String s = "SELECT  * FROM doctors";
            BasicRowProcessor basicRowProcessor = new BasicRowProcessor(new GenerousBeanProcessor());
            QueryRunner queryRunner = new QueryRunner();
            List<Doctors> query = queryRunner.query(conn, s,
                    new BeanListHandler<>(Doctors.class, basicRowProcessor));
            DruidUtils.close(null, conn);
            return query;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            DruidUtils.close(null, conn);
        }
        return null;
    }

    @Override
    public int update(Doctors doctors) {
        Connection conn = null;
        try {
            conn = DruidUtils.getConnection();

            String s = "update doctors set department=?, title=? where id=?";
            QueryRunner queryRunner = new QueryRunner();
            int update = queryRunner.update(conn, s,
                    doctors.getDepartment(), doctors.getTitle(), doctors.getId());
            DruidUtils.close(null, conn);
            return (update);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            DruidUtils.close(null, conn);
        }
        return 0;
    }

    @Override
    public int deleteById(Integer id) {
        return 0;
    }
}
